﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.HtmlControls;
using System.Data;

namespace PS.WebParts.Rollup.Custom.UI.WebControls.WebParts
{
    public class TelerikGridToolPart : ToolPart
    {
        #region Properties 
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RollupColumnInfo[]));
        private UI.WebControls.WebParts.TelerikGridWebPart telerikGridWebPart;

        private string FieldName = "psColumnMap";

        private List<RollupColumnInfo> columnsInfo = null;

        public List<RollupColumnInfo> ColumnsInfo
        {
            get
            {
                if (columnsInfo == null) columnsInfo = telerikGridWebPart.GetColumnInfo();
                return columnsInfo;
            }
            set { columnsInfo = value; }
        } 
        #endregion

        #region Constructors
        public TelerikGridToolPart(UI.WebControls.WebParts.TelerikGridWebPart telerikGridWebPart)
        {
            // TODO: Complete member initialization
            this.telerikGridWebPart = telerikGridWebPart;
        }
        
        #endregion

        #region Event Handlers 
        public override void ApplyChanges()
        {
            this.EnsureChildControls();

            string val = this.Page.Request.Form[FieldName];

            if (!string.IsNullOrEmpty(val))
            {
                var bytes = Encoding.ASCII.GetBytes(val);

                var obj = serializer.ReadObject(new MemoryStream(bytes));

                if (obj is RollupColumnInfo[])
                {
                    telerikGridWebPart.ColumnInfoList = val;
                    this.ColumnsInfo = new List<RollupColumnInfo>((RollupColumnInfo[])obj);
                }
            }

            telerikGridWebPart.ReBindControl();
        }

        public override void SyncChanges()
        {
            this.ColumnsInfo = telerikGridWebPart.GetColumnInfo();

            base.SyncChanges();
        }

        protected override void RenderToolPart(System.Web.UI.HtmlTextWriter output)
        {
            this.Page.ClientScript.RegisterHiddenField(FieldName, SPHttpUtility.NoEncode(this.GetJsonData()));

            HtmlButton btn = new HtmlButton();
            btn.CausesValidation = false;
            btn.InnerText = "Edit Columns";


            btn.Attributes.Add("onclick",
                               string.Format("window.open('{0}/_Layouts/PS.WebParts.Rollup.Custom/ColumnConfig.htm','psgrideditor','status=no,toolbar=no,location=no,menubar=no,resizable=yes,scrollbars=yes,width=350px,height=700px');return false;",
                                             SPContext.Current.Web.Url));
            this.Controls.Add(btn);

            base.RenderToolPart(output);
        } 
        #endregion

        string GetJsonData()
        {
            var rawDataSet = (from c in ColumnsInfo orderby c.Order select c).ToArray();

            MemoryStream ms = new MemoryStream();

            serializer.WriteObject(ms, rawDataSet);

            string json = Encoding.Default.GetString(ms.ToArray());

            return json;
        }
    }

    [DataContract]
    public class RollupColumnInfo
    {
        public RollupColumnInfo()
        {

        }

        [DataMember]
        public string Header { get; set; }

        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Hidden { get; set; }
        [DataMember]
        public string ColType { get; set; }

        [DataMember]
        public KeyValuePair<string, string>[] LinkSources { get; set; }

        [DataMember]
        public string LinkPattern { get; set; }

        [DataMember]
        public KeyValuePair<string, string>[] TextSources { get; set; }

        [DataMember]
        public string TextPattern { get; set; }

        [DataMember]
        public int Order { get; set; }
    }
}